var express = require("express")
var mongoose = require('mongoose')
const User = require('./models/User')
//模版
var swig = require('swig')
// 处理post的请求
var bodyParser = require('body-parser');
// 加载cookie
var Cookies = require('cookies')

// create app
var app = express()

app.use('/public', express.static(__dirname + "/public"))
app.engine('html', swig.renderFile)
// 设置view的目录
app.set('views', "./views")
app.set("view engine", "html")


// dev 取消模版缓存限制
swig.setDefaults({cache: false})

// bodyparser设置
app.use(bodyParser.urlencoded({extended: true}))

app.use( function(request, response, next) {
    request.cookies = new Cookies(request, response)
    request.userInfo = {}
    if (request.cookies.get("userInfo")) {
        console.log("request cookies:", request.cookies.get("userInfo"))
        try {
            request.userInfo = JSON.parse(request.cookies.get("userInfo"))
            // 判断当前用户是否管理员
            User.findById(request.userInfo.id).then(function(user) {
                request.userInfo.isAdmin = Boolean(user.isAdmin)
                next()
            })
        } catch(e) {
            next()
        }
    } else {
        next()
    }
})


app.use(function(request, response, next) {
    console.log("AAA", request.url)
    next()
})

// homepage
app.use('/admin', require('./routers/admin'))
app.use('/api', require('./routers/api'))

app.get('/', function(request, response, next) {

    console.log("render home", request.userInfo)
    response.render('main/index', {
        userInfo: request.userInfo
    })
})



mongoose.connect('mongodb://localhost:27017/blog', err => {
    if (err) {
        console.log('数据库连接失败')
    } else {
        console.log('数据库连接成功')
        console.log('start at localhost:8082')        
        app.listen(8082)
    }
})
// listen http request
// app.listen(8081)